<?php
/*
 * @Descripttion: 
 * @Author: Twoknives
 * @Date: 2023-11-13 22:27:57
 * @LastEditTime: 2023-11-16 22:07:58
 * @FilePath: \file-manage\app\common\controller\ApiController.php
 */

namespace app\common\controller;

use app\api\controller\Auth;
use app\api\model\Agent;
use app\api\model\ServerUser;
use app\api\model\Token;
use app\api\model\User;
use app\BaseController;
use think\exception\HttpResponseException;
use think\facade\Db;
use think\Model;
use think\Response;

/**
 * Class AdminController
 * @package app\common\controller
 */
class ApiController extends BaseController
{

    use \app\common\traits\JumpTrait;

    //token
    protected $token = '';
    //用户 id
    protected $uid = 0;

    protected $role_key = '';

    protected $dept_id = '';

    protected $method = '';

    protected $u_type = 1;

    /**
     * 无需登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 需要登录的方法
     * @var array
     */
    protected $mustLogin = [];

    protected $auth = null;

    protected $responseType = 'json';

    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFields = [
        'status',
        'sort',
        'remark',
        'is_delete',
        'is_auth',
        'status_text',
    ];

    /**
     * 当前模型
     * @Model
     * @var object
     */
    protected $model;

    /**
     * 不导出的字段信息
     * @var array
     */
    protected $noExportFields = ['delete_time', 'update_time'];

    /**
     * 初始化方法
     */
    protected function initialize()
    {
        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
        header("Access-Control-Allow-Headers:DNT,method,Method,tk-Method,X-Mx-ReqToken,Keep-Alive,XX-Api-Version,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");
        $token = $this->request->header('token');
        $method = $this->request->header('method');

        $this->method = $method;

        $this->auth = Auth::instance();

        if ($method !== 'tkAdmin' && $method !== 'tkh5' && $method !== 'tkwxapp') {
            $this->error('无权限！');
        }
        $userInfo = [];
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $is_token = Token::where('token', $token)->where('device_type', $method)->find();
            if (!$is_token) {
                $this->error('请先登录', null, 401);
            } else {
                $this->uid = $is_token['user_id'];
            }
            if (!$this->uid) {
                $this->error('请先登录', null, 401);
            }
             $userInfo = Db::name('sys_user')->where(['user_id' => $this->uid, 'del_flag' => 0])->find();
            if (empty($userInfo)) {
                $this->error('请检查用户账号是否正确', null, 444);
            }
            if ($userInfo['status'] != 0) {
                $this->error('账号被封禁，请联系客服处理', null, 444);
            }
        } else {
            $is_token = Token::where('token', $token)->where('device_type', $method)->find();
            if ($is_token) {
                $this->uid = $is_token['user_id'];
            }
        }

        parent::initialize();
    }

    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return array|bool|string|true
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg    提示信息
     * @param mixed $data   返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', $data = '', $success = true, array $header = [])
    {
        $code = 1;
        $result = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'success' => $success
        ];

        $type = $this->getResponseType();
        $header['Access-Control-Allow-Origin'] = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,method,Method,XX-Device-Type,XX-Token,Authorization,XX-Api-Version,XX-Wxapp-AppId';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response = Response::create($result, $type)->header($header);
        throw new HttpResponseException($response);
    }

    /** 
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg    提示信息,若要指定错误码,可以传数组,格式为['code'=>您的错误码,'msg'=>'您的错误消息']
     * @param mixed $data   返回的数据
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($data, $code, $msg, $type, $header);
    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType()
    {
        return 'json';
    }

    protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => time(),
            'data' => $data,
        ];

        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }

        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type, $code)->header($header);

        throw new HttpResponseException($response);
    }
}
